package br.mikhas.refractor.field;

/**
 * Check availability and gets the Unsafe object from sun internal classes
 * 
 * @author Mikhail Domanoski
 * 
 */
public class UnsafeGetter {

	/**
	 * Flags if the class is initialized
	 */
	private static boolean init = false;

	/**
	 * Flags if the Unsafe is available
	 */
	private static boolean available = false;

	/**
	 * Gets the unsafe object from sun internals
	 * 
	 * @return the Unsafe object or <code>null</code> if it is not available
	 */
	public static Unsafe getUnsafe() {
		if (isUnsafeAvailable())
			return Unsafe.getInstance();
		else
			return null;
	}

	/**
	 * Check if the unsafe object is available
	 */
	public static boolean isUnsafeAvailable() {
		if (!init)
			try {
				Class.forName("sun.misc.Unsafe");
				available = true;
			} catch (Throwable t) {
				available = false;
			}

		return available;
	}

}
